<template>
  <div class="role-container">
    <el-card style="width: 100%">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAdd">新增角色</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="角色名称">
          <el-input v-model="searchForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :row-class-name="tableRowClassName"
        table-layout="auto"
      >
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="name" label="角色名称" min-width="120" align="center" show-overflow-tooltip />
        <el-table-column prop="description" label="角色描述" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="pid" label="权限IDs" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" min-width="180" align="center" show-overflow-tooltip />
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
    >
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" type="textarea" :rows="3" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="权限IDs" prop="pid">
          <el-input v-model="roleForm.pid" placeholder="请输入权限IDs" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getRolesByPage, addRole, updateRole, deleteRole } from '@/api/role'

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 表格数据
const tableData = ref([])
const loading = ref(false)

// 获取角色列表
const fetchRoleList = async () => {
  try {
    loading.value = true
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      name: searchForm.name
    }
    const res = await getRolesByPage(params)
    if (res.success) {
      tableData.value = res.data.list
      total.value = res.data.total
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败：', error)
    // 只有在拦截器没有显示错误时才显示
    if (!error._showError) {
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '获取角色列表失败')
      } else {
        ElMessage.error('获取角色列表失败，请稍后重试')
      }
    }
  } finally {
    loading.value = false
  }
}

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const roleFormRef = ref(null)

// 角色表单
const roleForm = reactive({
  id: null,
  name: '',
  description: '',
  pid: '',
  permissions: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入角色描述', trigger: 'blur' }
  ]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchRoleList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  currentPage.value = 1
  handleSearch()
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(roleForm, {
    id: null,
    name: '',
    description: '',
    pid: '',
    permissions: ''
  })
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    description: row.description,
    pid: row.pid,
    permissions: row.permissions
  })
  dialogVisible.value = true
}

// 删除角色
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该角色吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await deleteRole(row.id)
    if (res.success) {
      ElMessage.success('删除成功')
      if (tableData.value.length === 1 && currentPage.value > 1) {
        currentPage.value--
      }
      fetchRoleList()
    } else if (!res._showError) {
      // 只有在拦截器没有显示错误时才显示
      ElMessage.error(res.msg || '删除角色失败')
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('删除角色失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '删除角色失败')
      } else {
        ElMessage.error('删除角色失败，请稍后重试')
      }
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!roleFormRef.value) return
  
  try {
    await roleFormRef.value.validate()
    
    let res;
    if (dialogType.value === 'add') {
      res = await addRole(roleForm)
      if (res.success) {
        ElMessage.success('添加成功')
        dialogVisible.value = false
        fetchRoleList()
      } else if (!res._showError) {
        // 只有在拦截器没有显示错误时才显示
        ElMessage.error(res.msg || '添加角色失败')
      }
    } else {
      res = await updateRole(roleForm)
      if (res.success) {
        ElMessage.success('更新成功')
        dialogVisible.value = false
        fetchRoleList()
      } else if (!res._showError) {
        // 只有在拦截器没有显示错误时才显示
        ElMessage.error(res.msg || '更新角色失败')
      }
    }
  } catch (error) {
    if (error !== 'cancel' && !error._showError) {
      console.error('提交表单失败：', error)
      // 只有在拦截器没有显示错误时才显示
      if (error.response && error.response.data) {
        ElMessage.error(error.response.data.msg || '提交失败')
      } else {
        ElMessage.error('提交失败，请检查表单内容')
      }
    }
  }
}

// 页面大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRoleList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchRoleList()
}

// 表格行样式
const tableRowClassName = ({ rowIndex }) => {
  return rowIndex % 2 === 0 ? '' : 'row-stripe'
}

// 初始化
onMounted(() => {
  fetchRoleList()
})
</script>

<style scoped>
.role-container {
  width: 100%;
  overflow: hidden;
  display: flex;
  padding: 0;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__header) {
  width: 100% !important;
}

:deep(.el-scrollbar__wrap) {
  overflow-x: hidden !important;
}

.row-stripe {
  background-color: #fafafa;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-card__body) {
  padding: 15px 20px;
  box-sizing: border-box;
  width: 100%;
}
</style> 